package com.github.hiling.auth.mapper;

import com.github.hiling.auth.model.AccessToken;
import com.github.hiling.auth.model.RevokeToken;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface AccessTokenMapper {
    @Select("""
            select refresh_token as refreshToken
            from oauth_access_token
            where access_token = #{accessToken}
            """)
    String getRefreshToken(@Param("accessToken") String accessToken);

    @Select("""
            <script>
                <foreach collection="list" item="item" index="index" separator="union all">
                    select access_token as accessToken
                    from oauth_access_token
                    where client_id = #{item.clientId}
                    <if test="item.userId != null">
                        and user_id = #{item.userId}
                    </if>
                    <![CDATA[ and create_time < #{item.time} ]]>
                </foreach>
            </script>
            """)
    List<String> getRevokeAccessToken(List<RevokeToken> list);

    @Insert("""
            insert into oauth_access_token
            (
               `client_id`,
                `user_id`,
                `access_token` ,
                `jwt_token`,
                `refresh_token`,
                `expires_in` ,
                `create_time`
            )
            values
            (
                #{clientId},
                #{userId},
                #{accessToken},
                #{jwtToken},
                #{refreshToken},
                #{expiresIn},
                #{createTime}
            )
            """)
    Long insert(AccessToken accessToken);

    @Delete("""
           <script>
                delete from oauth_access_token where access_token in
                <foreach item="accessToken" index="index" collection="accessTokenList"
                         open="(" separator="," close=")">
                    #{accessToken}
                </foreach>
           </script>
            """)
    void batchDeleteByAccessToken(@Param("accessTokenList") List<String> accessTokenList);

    @Delete("delete from oauth_access_token where create_time < date_sub(now(), INTERVAL expires_in second);")
    void deleteExpiredAccessToken();
}
